import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:simple_pwd_node/entity/record.dart';
import 'package:simple_pwd_node/model/record_model.dart';
import 'package:simple_pwd_node/util/db_utils.dart';
import 'package:simple_pwd_node/util/my_log.dart';
import 'package:uuid/uuid.dart';

class AddNewPage extends StatefulWidget {

  final String mode;

  final Record editRecord;

  const AddNewPage({Key key, this.mode, this.editRecord}) : super(key: key);

  @override
  _AddNewPageState createState() => _AddNewPageState();
}

class _AddNewPageState extends State<AddNewPage> {

  final _formKey = GlobalKey<FormState>();

  TextEditingController _accountTextController = new TextEditingController();
  TextEditingController _pwdTextController = new TextEditingController();
  TextEditingController _remarkTextController = new TextEditingController();
  TextEditingController _nameTextController = new TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.mode == 'edit'){
      Record editR = widget.editRecord;
      _accountTextController.text = editR.account;
      _pwdTextController.text = editR.password;
      _remarkTextController.text = editR.remark;
      _nameTextController.text = editR.name;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: false,
          title: Text(widget.mode == 'edit'?'编辑':'添加'),
          actions: [
            //fingerprint_sharp
            IconButton(
                icon: Icon(Icons.check),
                onPressed: _save
            )
          ],
        ),
        body: Container(
            color: Color(0xfff5f5f5),
            padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                      margin: EdgeInsets.only(top: 20),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: [
                          Text(
                            '账号：',
                            style: TextStyle(fontSize: 18),
                          ),
                          Expanded(
                              child: TextFormField(
                                controller: _accountTextController,
                                decoration: InputDecoration(hintText: '输入账号'),
                                validator: (String value) {
                                  return value.length > 0 ? null : '账号不得为空哦';
                                }
                          ))
                        ],
                      )),
                  Container(
                      margin: EdgeInsets.only(top: 20),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: [
                          Text('密码：', style: TextStyle(fontSize: 18),),
                          Expanded(child: TextFormField(
                              controller: _pwdTextController,
                              decoration: InputDecoration(hintText: '输入密码'),
                              validator: (String value) {
                                return value.length > 0 ? null : '密码不得为空哦';
                              }
                          ))
                        ],
                      )),
                  Container(
                      margin: EdgeInsets.only(top: 20),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: [
                          Text('备注：', style: TextStyle(fontSize: 18)),
                          Expanded(child: TextFormField(
                              controller: _accountTextController,
                              decoration: InputDecoration(hintText: '输入备注'),
                          ))
                        ],
                      )),
                  Container(
                      margin: EdgeInsets.only(top: 20),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: [
                          Text('网站：', style: TextStyle(fontSize: 18)),
                          Expanded(child: TextFormField(
                              controller: _nameTextController,
                              decoration: InputDecoration(hintText: '输入网站'),
                          ))
                        ],
                      )),
                  widget.mode == 'edit'?ElevatedButton(onPressed: (){
                    _delete();
                  },
                    child: Text('删除'),
                  ):Container()
                ],
              ),
            )
        )
    );
  }

   _save()async{
    var state = _formKey.currentState;
    if(state.validate()){
      state.save();
      if(widget.mode == 'edit'){
        var newRecord = new Record(id:widget.editRecord.id,name:_nameTextController.text,account:_accountTextController.text,password:_pwdTextController.text,remark: _remarkTextController.text);
        var db = await DbUtils.getInstance().openDb("db1");
        await db.updateItem(newRecord, "id", widget.editRecord.id);
        await Provider.of<RecordModel>(context, listen: false).update();
      }else{
        var uuid = Uuid();
        var record = new Record(id:uuid.v1().toString(),name:_nameTextController.text,account:_accountTextController.text,password:_pwdTextController.text,remark: _remarkTextController.text);
        var db = await DbUtils.getInstance().openDb("db1");
        await db.insertItem(record);
        await Provider.of<RecordModel>(context, listen: false).update();
        Navigator.of(context).pop();
      }
    }
  }

  _alertDialog() async {
    var alertDialogs = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("确定要删除吗"),
            actions: <Widget>[
              ElevatedButton(
                  child: Text("取消"),
                  onPressed: () => Navigator.pop(context, false)),
              ElevatedButton(
                  child: Text("确定"),
                  onPressed: () => Navigator.pop(context, true)),
            ],
          );
        });
    return alertDialogs;
  }

  _delete()async{
    var confirmDelete = await _alertDialog();
    if(confirmDelete){
      var db = await DbUtils.getInstance().openDb("db1");
      await db.deleteItem(widget.editRecord,key: "id",value: widget.editRecord.id);
      await Provider.of<RecordModel>(context, listen: false).update();
      Navigator.of(context).pop();
    }
  }
}
